import Vue from 'vue'
import { Toast } from 'vant'
import store from '@/store';
import {TokenKey} from "@utils/auth"

Vue.use(Toast)
import axios from 'axios'
import baseApi from './baseApi'
import { showFullScreenLoading, tryHideFullScreenLoading } from './loading'
import { fnHandelError } from './error'
import Qs from 'qs';
import { blobData } from './blobData'

axios.defaults.withCredentials = true
// create an axios instance
const service = axios.create(baseApi)

let axiosPromiseObj = {}
let startTime = +new Date()
let endTime
let cancelRequest

// request interceptor
service.interceptors.request.use(
  config => {
    endTime = +new Date()
    config.cancelToken = new axios.CancelToken(function(c) {
      cancelRequest = c
    })
    // 判断是否多次连续请求
    if (
      axiosPromiseObj['url'] === config.url &&
      axiosPromiseObj['data'] === config.data &&
      axiosPromiseObj['params'] === config.params &&
      endTime - startTime < 600
    ) {
      cancelRequest({ message: 'CancelToken', url: config.url })
    } else {
      axiosPromiseObj['url'] = config.url
      axiosPromiseObj['data'] = config.data
      axiosPromiseObj['params'] = config.params
      startTime = endTime
      // loading ，默认没有hideLoading参数，添加loading
      if (!config.hideLoading) {
        showFullScreenLoading()
      }
    }

    const isUpload = config.data instanceof FormData && config.data.get('file') instanceof File;
    if (config.method === 'post' && !isUpload) {
      config.transformRequest[0] = function (data) {
        // 对 data 进行任意转换处理
        return Qs.stringify(data);
      };
    }

    if (store.getters.token) {
      config.headers[TokenKey] = store.getters.token;
    }

    return config
  },
  error => {
    tryHideFullScreenLoading()
    window.console.log(JSON.stringify(error)) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    startTime = +new Date()
    if (!response.config.hideLoading) {
      tryHideFullScreenLoading()
    }

    // console.log('resType', Object.prototype.toString.call(res), Object.prototype.toString.call(res.data), res);

    // 文件下载
    if (/blob/i.test(response.config.responseType)) { // blob、json
      return blobData(response);
    }

    
    // 状态处理
    let { code, message } = response.data
    if (code === 1000) {
      return response.data
    } else {
      fnHandelError.call(service, 'infoError', response)
      let err = response.config.url + ':' + message
      return Promise.reject(err)
    }
  },
  error => {
    startTime = +new Date()
    if (error.message && error.message.msg !== 'CancelToken') {
      tryHideFullScreenLoading()
      fnHandelError.call(service, 'httpError', error)
      return Promise.reject(error)
    } else {
      return Promise.reject(error)
    }
  }
)

export default service
